import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/state/common_net_status.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/fullscreen_loading_overlay.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/me/application/notification/service_post_notifier.dart';
import 'package:casdon/modules/me/application/notification/service_product_list_notifier.dart';
import 'package:casdon/modules/me/ui/widgets/form_field_item.dart';
import 'package:casdon/modules/me/ui/widgets/mouth_day_week_picker.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:flutter_pickers/address_picker/locations_data.dart';
import 'package:flutter_pickers/pickers.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:casdon/modules/me/data/repository/me_repository_impl.dart';
import 'package:flutter/services.dart';

const Map<String, int> repairServiceOrderParams = {"type": 1, "category": 4};

@RoutePage()
class ServiceRepairScreen extends ConsumerStatefulWidget {
  final String? devId; // 可选的涂鸦设备ID
  final bool standalone; // 是否作为独立页面展示（带AppBar）
  final String? title; // 独立页面标题
  final bool isFromNative; // 原生入口标记
  const ServiceRepairScreen({
    super.key,
    this.devId,
    this.standalone = true,
    this.title = '预约维修',
    this.isFromNative = false,
  });

  @override
  ConsumerState<ServiceRepairScreen> createState() => _ServiceRepairState();
}

class _ServiceRepairState extends ConsumerState<ServiceRepairScreen> {
  late final TextEditingController _contactController;
  late final TextEditingController _phoneController;
  late final TextEditingController _addressController;
  late final TextEditingController _memoController;
  late final TextEditingController _orderNumController;
  late final ProviderSubscription _subscription;
  final providerInstance = servicePostOrderNotifierProvider(
    repairServiceOrderParams,
  );
  void _dismissKeyboard() {
    //FocusScope.of(context).unfocus();
  }

  @override
  void initState() {
    super.initState();

    _contactController = TextEditingController(
      text: ref.read(providerInstance).contact ?? '',
    );

    _phoneController = TextEditingController(
      text: ref.read(providerInstance).phone ?? '',
    );

    _addressController = TextEditingController(
      text: ref.read(providerInstance).address ?? '',
    );

    _memoController = TextEditingController(
      text: ref.read(providerInstance).memo ?? '',
    );

    _orderNumController = TextEditingController(
      text: ref.read(providerInstance).orderNum ?? '',
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadInitialData();
      if (widget.standalone) {
        try {
          const MethodChannel(
            'native_to_flutter',
          ).invokeMethod('enableInteraction');
        } catch (_) {}
      }
    });
    _setupStateListener();
  }

  Future<void> _loadInitialData() async {
    try {
      if (widget.devId == null) return;
      // 单引擎多VC：Provider共享，直接使用即可
      final data = await ref.read(serviceProductListProvider.future);

      // 如有 devId，自动匹配并填充产品
      final devId = widget.devId;
      if (devId == null || devId.isEmpty) return;
      final repo = ref.read(meRepositoryProvider);
      final info = await repo.getTuyaDeviceInfo(devId: devId);
      final model = (info?['model'] ?? '').toString().trim();
      if (model.isEmpty) return;
      if (data.isEmpty) return;

      final target = model.toLowerCase();
      for (final category in data) {
        for (final p in category.products) {
          if (p.name.trim().toLowerCase() == target) {
            // 更新选择到状态
            ref.read(providerInstance.notifier).updateProduct(p);
            return;
          }
        }
      }
    } catch (e) {
      if (mounted) {
        ToastUtil.show(e.toString());
      }
    }
  }

  @override
  void dispose() {
    _subscription.close();

    _contactController.dispose();
    _phoneController.dispose();
    _addressController.dispose();
    _memoController.dispose();
    _orderNumController.dispose();
    super.dispose();
  }

  Future<void> _trySystemBackOrNative() async {
    try {
      const MethodChannel('native_to_flutter').invokeMethod('nativePop');
    } catch (_) {}
  }

  @override
  Widget build(BuildContext context) {
    final isLoading = widget.standalone
        ? ref.watch(
            providerInstance.select((s) => s.status == CommonNetStatus.loading),
          )
        : false;

    final Widget content = SingleChildScrollView(
      child: Container(
        color: Colors.white,
        child: Column(
          children: [
            _buildGap(context),
            FormFieldItem(
              label: '报修产品',
              hintText: '请选择',
              isEditable: false,
              showArrow: true,
              watchProvider: providerInstance.select((s) => s.product),
              onTap: () async {
                _dismissKeyboard();

                final result = await ServiceProductListRoute().push(context);
                ref.read(providerInstance.notifier).updateProduct(result);
              },
            ),
            FormFieldItem(
              label: '期望服务时间',
              hintText: '请选择',

              isEditable: false,
              showArrow: true,
              watchProvider: providerInstance.select((s) => s.expectTime),
              onTap: () {
                _dismissKeyboard();
                DatePicker.showPicker(
                  context,
                  showTitleActions: true,
                  pickerModel: MouthDayWeekPicker(
                    minTime: DateTime.now(),
                    maxTime: DateTime.now().add(const Duration(days: 30)),
                    currentTime: DateTime.now(),
                    locale: LocaleType.zh,
                  ),
                  locale: LocaleType.zh,
                  onConfirm: (date) {
                    ref.read(providerInstance.notifier).updateExpectTime(date);
                  },
                );
              },
            ),
            _buildGap(context),
            FormFieldItem(
              label: '联系人',
              hintText: '请输入',
              isEditable: true,
              controller: _contactController,
              watchProvider: providerInstance.select((s) => s.contact),
              onChanged: (val) =>
                  ref.read(providerInstance.notifier).updateContactName(val),
            ),
            FormFieldItem(
              label: '联系电话',
              hintText: '请输入',
              controller: _phoneController,
              isEditable: true,
              keyboardType: TextInputType.phone,
              watchProvider: providerInstance.select((s) => s.phone),
              onChanged: (val) =>
                  ref.read(providerInstance.notifier).updateContactPhone(val),
            ),
            FormFieldItem(
              label: '所在地区',
              hintText: '请选择',

              isEditable: false,
              showArrow: true,
              watchProvider: providerInstance.select((s) => s.location),
              onTap: () async {
                _dismissKeyboard();
                Pickers.showAddressPicker(
                  context,
                  addAllItem: false,
                  overlapTabBar: true,
                  initProvince: '广东省',
                  initCity: '深圳市',
                  initTown: '罗湖区',
                  onConfirm: (p, c, t) {
                    final List<String> codes = Address.getCityCodeByName(
                      provinceName: p,
                      cityName: c,
                      townName: t,
                    );
                    ref
                        .read(providerInstance.notifier)
                        .updateProvince(codes.first, p);
                    ref.read(providerInstance.notifier).updateCity(codes[1], c);
                    ref
                        .read(providerInstance.notifier)
                        .updateCounty(codes[2], t!);
                    ref
                        .read(providerInstance.notifier)
                        .updateLocation('$p$c$t');
                  },
                );
              },
            ),
            FormFieldItem(
              label: '详细地址',
              hintText: '请输入',
              controller: _addressController,
              isEditable: true,
              watchProvider: providerInstance.select((s) => s.address),
              onChanged: (val) =>
                  ref.read(providerInstance.notifier).updateAddress(val),
            ),
            _buildGap(context),
            FormFieldItem(
              label: '备注',
              hintText: '可描述机器故障等信息',
              controller: _memoController,
              isEditable: true,
              layoutDirection: Axis.vertical,
              maxLines: 4,
              watchProvider: providerInstance.select((s) => s.memo),
              onChanged: (val) =>
                  ref.read(providerInstance.notifier).updateMemo(val),
            ),
            FormFieldItem(
              label: '购买渠道',
              hintText: '请选择',
              isEditable: false,
              showArrow: true,
              watchProvider: providerInstance.select((s) => s.channel),
              onTap: () async {
                _dismissKeyboard();
                final result = await ServiceChannelListRoute().push(context);
                ref.read(providerInstance.notifier).updateChannel(result.name);
              },
            ),
            FormFieldItem(
              label: '购买日期',
              hintText: '请选择',
              isEditable: false,
              showArrow: true,
              watchProvider: providerInstance.select((s) => s.buyDate),
              onTap: () {
                _dismissKeyboard();
                DatePicker.showDatePicker(
                  context,
                  showTitleActions: true,
                  minTime: DateTime(2015, 1, 1),
                  maxTime: DateTime.now(),
                  currentTime: DateTime.now(),
                  locale: LocaleType.zh,
                  onConfirm: (date) {
                    ref.read(providerInstance.notifier).updateBuyDate(date);
                  },
                );
              },
            ),
            FormFieldItem(
              label: '平台单号',
              hintText: '请输入',
              controller: _orderNumController,
              isEditable: true,
              watchProvider: providerInstance.select((s) => s.orderNum),
              onChanged: (val) =>
                  ref.read(providerInstance.notifier).updateOrderNumber(val),
            ),
            const SizedBox(height: 30),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: PrimaryButton(
                text: "提交",
                onPressed: () => ref.read(providerInstance.notifier).submit(),
              ),
            ),
            const SizedBox(height: 30),
          ],
        ),
      ),
    );
    // 独立页面：带导航栏
    final body = SafeArea(child: content);

    if (widget.standalone) {
      final page = WillPopScope(
        onWillPop: () async {
          await _trySystemBackOrNative();
          return true;
        },
        child: Scaffold(
          backgroundColor: Colors.white,
          appBar: CommonAppBar(
            title: widget.title ?? '预约维修',
            onBack: () => _trySystemBackOrNative(),
          ),
          body: body,
        ),
      );
      return FullscreenLoadingOverlay(loading: isLoading, child: page);
    }

    // 作为 TabBarView 子页面时，补充 Material 上下文以满足 TextField 等组件依赖
    return Material(color: Colors.white, child: body);
  }

  Widget _buildGap(BuildContext context) {
    return ColoredBox(
      color: context.colorScheme.surface,
      child: SizedBox(height: 8, width: double.infinity),
    );
  }

  void _setupStateListener() {
    _subscription = ref.listenManual(providerInstance, (previous, next) {
      if (next.status == CommonNetStatus.success) {
        ToastUtil.show(next.msg ?? "提交成功");
        final s = ref.read(providerInstance);
        final productName = s.product ?? '';
        String expect = '';
        if (s.expectTime != null && s.expectTime!.isNotEmpty) {
          expect = s.expectTime!;
        }
        ServiceSubmitSuccessRoute(
          productName: productName,
          expectTime: expect,
        ).push(context).then((val) {
          if (val == 'main' && context.mounted) {
            if (widget.standalone) {
              _trySystemBackOrNative();
            } else {
              context.router.popUntilRouteWithName(TabRoute.name);
            }
          }
        });
      } else if (next.status == CommonNetStatus.failure) {
        ServiceSubmitFailureRoute(message: next.msg).push(context).then((val) {
          if (val == 'main' && context.mounted) {
            if (widget.standalone) {
              _trySystemBackOrNative();
            } else {
              context.router.popUntilRouteWithName(TabRoute.name);
            }
          }
        });
      }
    });
  }
}
